from django.shortcuts import render
from django.views import View


#
class AreaView(View):
    def get(self, request):
        """获取区域信息"""
        # 查新数据库
        try:
            area_li = Area.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='数据库异常')
        area_dict_li = []
        for area in area_li:
            area_dict_li.append(area.to_dict())
        return jsonify(errno=RET.OK, errmsg='OK', data=area_dict_li)


class HourseView(View):

    # def save_house_info():
        """保存房屋的基本信息：发布
        前端发送过来的json数据
        {
            "title": "",
            "price": "",
            "area_id": "",
            "address": "",
            "room_count": "",
            "acreage": "",
            "unit": "",
            "capacity": "",
            "beds": "",
            "deposit": "",
            "min_days": "",
            "max_days": "",
            "facility": ["7", "8"]
        }
        """
        # 获取数据
        # user_id = g.user_id
        #
        # house_data = request.get_json()
        #
        # title = house_data.get('title')  # 标题
        # price = house_data.get('price')  # 单价
        # area_id = house_data.get('area_id')  # 区域的编号
        # address = house_data.get('address')  # 地址
        # room_count = house_data.get('room_count')  # 房间数
        # acreage = house_data.get('acreage')  # 面积
        # unit = house_data.get('unit')  # 布局（几厅几室）
        # capacity = house_data.get('capacity')  # 可容纳人数
        # beds = house_data.get('beds')  # 卧床数目
        # deposit = house_data.get('deposit')  # 押金
        # min_days = house_data.get('min_days')  # 最小入住天数
        # max_days = house_data.get('max_days')  # 最大入住天数
        #
        # # 校验必填参数，facility非必填
        # if not all(
        #         [title, price, area_id, address, room_count, acreage, unit, capacity, beds, deposit, min_days, max_days]):
        #     return jsonify(errno=RET.PARAMERR, errmsg='参数不完整')

        # 对单价和押金作出判断，是否是数字，判断方法：可否转换成数字
        # try:
        #     price = int(float(price) * 100)
        #     deposit = int(float(deposit) * 100)
        # except Exception as e:
        #     current_app.logger.error(e)
        #     return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

        # # 判断城区是否存在，防止发布的城区在数据库中没有，进行过滤操作
        # try:
        #     area = Area.query.get(area_id)
        # except Exception as e:
        #     current_app.logger.error(e)
        #     return jsonify(errno=RET.DBERR, errmsg='数据异常')
        #
        # # 如果城区在数据库中不存在
        # if area is None:
        #     return jsonify(errno=RET.NODATA, errmsg='城区信息有误')

        # 其他验证，略

        # # 保存数据
        # house = House(
        #     user_id=user_id,
        #     area_id=area_id,
        #     title=title,
        #     price=price,
        #     room_count=room_count,
        #     address=address,
        #     acreage=acreage,
        #     unit=unit,
        #     capacity=capacity,
        #     beds=beds,
        #     deposit=deposit,
        #     min_days=min_days,
        #     max_days=max_days
        # )

        # 处理房屋设施信息
#         facility_ids = house_data.get('facility')
#
#         # 如果用户勾选了设施信息，再保存到数据库
#         if facility_ids:
#             # ["7", "8", ..]
#             # 过滤出设施数据在数据库中存在的数据
#             try:
#                 facilities = Facility.query.filter(Facility.id.in_(facility_ids)).all()
#             except Exception as e:
#                 current_app.logger.error(e)
#                 return jsonify(errno=RET.DBERR, errmsg='数据库异常')
#
#             if facilities:
#                 # 表示有合法的设施数据
#                 # 保存数据库
#                 house.facilities = facilities
#         try:
#             db.session.add(house)
#             db.session.commit()
#         except Exception as e:
#             current_app.logger.error(e)
#             db.session.rollback()
#             return jsonify(errno=RET.DBERR, errmsg='保存数据错误')
#
#         # 保存数据成功
#         return jsonify(errno=RET.OK, errmsg='保存数据成功', data={"house_id": house.id})
#
#
#     def save_house_image():
#         """保存房屋图片
#         参数：图片，房屋的id
#         """
#         image_file = request.files.get("house_image")
#         house_id = request.form.get('house_id')
#
#         # 验证参数的完整性
#         if not all([image_file, house_id]):
#             return jsonify(errno=RET.PARAMERR, errmsg='参数不完整')
#
#         # 判断房屋是否存在
#         try:
#             house = House.query.get(house_id)
#         except Exception as e:
#             current_app.logger.error(e)
#             return jsonify(errno=RET.DBERR, errmsg='数据库异常')
#
#         if house is None:
#             return jsonify(errno=RET.NODATA, errmsg='房屋不存在')
#
#         # 保存图片到七牛
#         image_data = image_file.read()
#         try:
#             file_name = storage(image_data)
#         except Exception as e:
#             current_app.logger.error(e)
#             return jsonify(errno=RET.THIRDERR, errmsg='上传图片失败')
#
#         # 保存图片到数据库
#         house_image = HouseImage(house_id=house_id, url=file_name)
#         db.session.add(house_image)
#
#         # 处理房屋的主图片
#         if not house.index_image_url:
#             house.index_image_url = file_name
#             db.session.add(house)
#
#         try:
#             db.session.commit()
#         except Exception as e:
#             current_app.logger.error(e)
#             db.session.rollback()
#             return jsonify(errno=RET.DBERR, errmsg='保存图片异常')
#
#         # 返回结果
#         image_url = constants.QINIU_URL_DOMAIN + file_name
#         return jsonify(errno=RET.OK, errmsg='OK', data={"image_url": image_url})
#
# class UserHourseView(View):

    # start_date = request.args.get("sd", "")  # 起始时间
    # end_date = request.args.get("ed", "")  # 结束时间
    # area_id = request.args.get("aid", "")  # 区域编号
    # sort_key = request.args.get("sk", "new")  # 排序关键字
    # page = request.args.get("p")  # 页数


    # if start_date:
    #     start_date = datetime.strptime(start_date, "%Y-%m-%d")
    #
    # if end_date:
    #     end_date = datetime.strptime(end_date, "%Y-%m-%d")
    #
    # if start_date and end_date:
    #     raise start_date <= end_date


    # if area_id:
#         try:
#             area = Area.query.get(area_id)
#         except Exception as e:
#             current_app.logger.error(e)
#             return jsonify(errno=RET.PARAMERR, errmsg='区域参数有误')
    # # 处理页数
    #     try:
    #         page = int(page)
    #     except Exception as e:
    #         current_app.logger.error(e)
    #         page = 1


            # 获取缓存数据
    # redis_key = "house_%s_%s_%s_%s" % (start_date, end_date, area_id, sort_key)
    #     try:
    #     resp_json = redis_store.hget(redis_key, page)
    #     except Exception as e:
    #     current_app.logger.error(e)
    #     else:
    #     if resp_json:

    # li = []
    #
    # House.query.filter(*li).all()